package com.blink.zookeeper.operate;

import com.blink.base.TestZK;
import com.blink.zookeeper.ZooKeeperCreator;
import org.apache.zookeeper.*;
import org.junit.jupiter.api.Test;

/**
 * <Description> 删除节点：只能删除叶子结点</Description>
 * <ClassName> TestZKDeleteNode</ClassName>
 *
 * @Author liuxianzhao
 * @Date 2018年01月12日 14:44
 */
public class TestZKDeleteNode extends TestZK {
    /**
     * <Title>testDeleteNodeSync</Title>
     * <Description> 测试同步删除节点</Description>
     *
     * @return void
     * @throws
     */
    @Test
    public void testDeleteNodeSync() throws KeeperException, InterruptedException {
        ZooKeeper zk = ZooKeeperCreator.getZk("testDeleteNodeSync");
        String nodeName = "/NODE";
        String realPath = zk.create(nodeName,
                "testdata".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        logger.info("创建节点:{},realPath:{}成功", nodeName, realPath);
        zk.delete(nodeName, -1);
        Thread.sleep(Integer.MAX_VALUE);
    }

    /**
     * <Title>testDeleteNodeASync</Title>
     * <Description> 测试异步删除节点</Description>
     *
     * @return void
     * @throws
     */
    @Test
    public void testDeleteNodeASync() throws KeeperException, InterruptedException {
        ZooKeeper zk = ZooKeeperCreator.getZk("testDeleteNodeSync");
        String nodeName = "/NODE";
        String realPath = zk.create(nodeName,
                "testdata".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        logger.info("创建节点:{},realPath:{}成功", nodeName, realPath);
        zk.delete(nodeName, -1, new DefaultVoidCallback(), "TestCTX");
        Thread.sleep(Integer.MAX_VALUE);
    }

    class DefaultVoidCallback implements AsyncCallback.VoidCallback {
        @Override
        public void processResult(int rc, String path, Object ctx) {
            if (KeeperException.Code.OK.intValue() == rc) {
                logger.info("删除成功: path-{},ctx-{}", path, ctx);
            } else {
                logger.error("删除失败:" + KeeperException.create(KeeperException.Code.get(rc), path).getMessage());
            }
        }
    }
}
